package com.example.demo.web.controller;

import com.example.demo.app.Response;
import com.example.demo.app.Validator;
import com.example.demo.web.entity.User;
import com.example.demo.web.service.UserV1Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
@RequestMapping("userV1")
public class UserV1Controller extends BaseController {

    @Autowired
    UserV1Service userService;


    @PostMapping("sendCaptchaV1")
    public Response sendCaptcha(String mobile) {
        // 手机号参数验证
        userService.isMobile(mobile);

        // 发送验证码
        userService.sendCaptcha(mobile);

        return success();
    }

    @PostMapping("sendCaptchaV2")
    public Response sendCaptcha(User user) {

        // 单独验证手机号参数
        Validator<User> validator = new Validator<>();
        validator.validateProperty(user, "mobile");

        // 发送验证码
        userService.sendCaptcha(user.getMobile());

        return success();
    }

    @PostMapping("login")
    public Response login(@Valid User user) {

        // 验证码是否有效
        userService.validCaptcha(user.getMobile(), user.getCaptcha());

        // 手机号是否注册
        if (userService.mobileExist(user.getMobile())) {
            user = userService.reLogin(user.getMobile());
            return success(user);
        }

        user = userService.register(user.getMobile());

        return success(user);
    }

}
